<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['trade:operatorUser:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="运营商编码" align="center" prop="operatorCode" />
      <el-table-column label="运营商名称" align="center" prop="operatorName" />
      <el-table-column label="联系人名称" align="center" prop="userName" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="身份证正面照片" align="center" prop="idCardFront" >
        <template slot-scope="{row}">
          <el-image v-if="row.idCardFront"
            style="width: 100px; height: 100px"
            :src="row.idCardFront" 
            :preview-src-list="[row.idCardFront]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="身份证背面照片" align="center" prop="idCardBack" >
        <template slot-scope="{row}">
          <el-image v-if="row.idCardBack"
            style="width: 100px; height: 100px"
            :src="row.idCardBack" 
            :preview-src-list="[row.idCardBack]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['trade:operatorUser:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="运营商名称" prop="operatorName">
              <el-input v-model="form.operatorName" clearable placeholder="请输入运营商名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人名称" prop="userName">
              <el-input v-model="form.userName" clearable placeholder="请输入联系人名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" clearable placeholder="请输入手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证正面照片" prop="idCardFront">
              <imageUpload v-model="form.idCardFront" :limit="1"></imageUpload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="身份证背面照片" prop="idCardBack">
              <imageUpload v-model="form.idCardBack" :limit="1"></imageUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <h2 class="flex_hcneter"><div style="color:red;">*</div>负责区域：<el-button type="primary" icon="el-icon-plus" @click="addList"></el-button></h2>
        <el-row :span="24" v-for="(areaItem,index) in form.areaList" :key="index">
          <el-col :span="6">
            <el-form-item label="省份" prop="provinceCode">
              <el-select v-model="areaItem.provinceCode" @change="(e)=>proviceChange(e,index)" filterable  placeholder="请选择省份">
                <el-option
                  v-for="item in proviceList"
                  :key="item.areaCode"
                  :label="item.name"
                  :value="item.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="市"  prop="cityCode">
              <el-select v-model="areaItem.cityCode" @change="(e)=>cityChange(e,index)" filterable placeholder="请选择市">
                <el-option
                  v-for="item in areaItem.cityList"
                  :key="item.areaCode"
                  :label="item.name"
                  :value="item.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区" prop="countyCode">
              <el-select v-model="areaItem.countyCode" @change="(e)=>areaChange(e,index)" filterable placeholder="请选择区">
                <el-option
                  v-for="item in areaItem.countyList"
                  :key="item.areaCode"
                  :label="item.name"
                  :value="item.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="街道" prop="townCode">
              <el-select v-model="areaItem.townCode" @change="(e)=>townChange(e,index)" clearable filterable placeholder="请选择街道">
                <el-option
                  v-for="item in areaItem.streetList"
                  :key="item.areaCode"
                  :label="item.name"
                  :value="item.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="areaItem.longitude" class="flex_flex" clearable placeholder="请输入经度"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude" >
              <div class="flex_hcneter">
                <el-input class="flex_flex" v-model="areaItem.latitude" clearable placeholder="请输入纬度"/>
                <el-button style="margin-left:15px;" type="primary" @click="amapSelect(areaItem,index)">获取位置</el-button>
                <el-button style="margin-left:10px;" type="primary" v-if="form.areaList.length > 1" @click="delList(index)" icon="el-icon-minus"></el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="申请原因" prop="content">
              <el-input v-model="form.content" clearable type="textarea" :rows="6" placeholder="请输入申请原因" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item  label="附件" prop="attachment">
          <FileUpload :limit="100"  v-model="form.picUrl" :fileType="null" :fileModel="2" fileName="files" ></FileUpload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="popLodding" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图弹窗 -->
    <mapLog ref="mapLogs" @mapSubmit="mapSubmit" :formObj="form" :formType="{
      'longitude':'longitude',
      'latitude':'latitude',
    }"></mapLog>
  </div>
</template>

<script>
import { listOperator, getOperator, addOperator, updateOperator, } from "@/api/operator/operatorList";
import { listByPCode, } from "@/api/address/area";
import mapLog from "@/components/mapLog/index";
import { validateMobile } from '@/utils/validate'
import Vue from 'vue'
export default {
  name: "OperatorList",
  dicts: [],
  components: { mapLog, },
  data() {
    return {
      popLodding:false,//弹窗加载
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [ { required: true, message: "联系人名称不能为空", trigger: "blur" } ],
        operatorName: [ { required: true, message: "运营商名称不能为空", trigger: "blur" } ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: validateMobile.bind(this), trigger: 'blur' },
        ],
        // provinceCode: [ { required: true, message: "省不能为空", trigger: "change" } ],
        // cityCode: [ { required: true, message: "市不能为空", trigger: "change" } ],
        // countyCode: [ { required: true, message: "区不能为空", trigger: "change" } ],
        idCardFront: [ { required: true, message: "身份证正面照片不能为空", trigger: "change" } ],
        idCardBack: [ { required: true, message: "身份证背面照片不能为空", trigger: "change" } ],
      },
      selectIndex:0,//选中负责区域下标
      proviceList:[],//省
      areaObj:{
        cityList:[],//市
        countyList:[],//区
        streetList:[],//街道
      },//负责区域添加对象
    };
  },
  created() {
    this.getList();
  },
  methods: {
    addList(){//添加列表
      this.form.areaList.push({...this.areaObj})
    },
    delList(index){//删除列表
      this.form.areaList.splice(index,1)
    },
    amapSelect(e,index){//地图打开
      this.selectIndex = index
    	this.$refs.mapLogs.mapLoad(e)
    },
    //地图选择保存
    mapSubmit(e){
      let form = {...this.form}
      form.areaList[this.selectIndex] = {...e}
      this.form = {...form}
    },
    proviceChange(e,index){// 省份下拉改变
      let form = {...this.form}
      let obj = this.proviceList.find(item=>item.areaCode == e)
      let areaList = [...form.areaList]
      areaList[index].provinceName = obj ? obj.name : ''
    	areaList[index].cityCode = ''
    	areaList[index].countyCode = ''
      areaList[index].townCode = ''
      areaList[index].cityList = []
    	areaList[index].countyList = []
      areaList[index].streetList = []
      form.areaList = [...areaList]
      this.form = {...form}
    	this.initLocationOptions(e,2,index)
    },
    cityChange(e,index) {// 市下拉改变
      let form = {...this.form}
      let areaList = [...form.areaList]
      let obj = areaList[index].cityList.find(item=>item.areaCode == e)
      areaList[index].cityName = obj ? obj.name : ''
      areaList[index].countyCode = ''
      areaList[index].townCode = ''
      areaList[index].countyList = []
      areaList[index].streetList = []
      form.areaList = [...areaList]
      this.form = {...form}
    	this.initLocationOptions(e,3,index)
    },
    areaChange(e,index){// 区下拉改变
      let form = this.$copyValue(this.form)
      let areaList = [...form.areaList]
      let obj = areaList[index].countyList.find(item=>item.areaCode == e)
      areaList[index].countyName = obj ? obj.name : ''
      areaList[index].townCode = ''
      areaList[index].streetList = []
      form.areaList = [...areaList]
      this.form = this.$copyValue(form)
    	this.initLocationOptions(e,4,index)
    },
    townChange(e,index){// 街道下拉改变
      let form = this.$copyValue(this.form)
      let areaList = [...form.areaList]
      let obj = areaList[index].streetList.find(item=>item.areaCode == e)
      areaList[index].townName = obj ? obj.name : ''
      form.areaList = [...areaList]
      this.form = this.$copyValue(form)
    },
    initLocationOptions(code,type,index) {// 初始化位置选项
      listByPCode(code).then(resp => {
        let form = {...this.form}
        if(type == 1) this.proviceList = resp.data || []
        if(type == 2) form.areaList[index].cityList = resp.data || []
        if(type == 3) form.areaList[index].countyList = resp.data || []
        if(type == 4) form.areaList[index].streetList = resp.data || []
        this.form = {...form}
      })
    },
    /** 查列表 */
    getList() {
      this.loading = true;
      listOperator(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {areaList:[{...this.areaObj}],};
      this.resetForm("form");
      this.initLocationOptions(0,1,0);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    async initLocationOptions1(code,type,index,areaList) {// 初始化位置选项
      let resp = await listByPCode(code)
      if(type == 2) areaList[index].cityList = resp.data || []
      if(type == 3) areaList[index].countyList = resp.data || []
      if(type == 4) areaList[index].streetList = resp.data || []

      if(type == 2) this.$set(areaList,'cityList',resp.data);
      if(type == 3) this.$set(areaList,'countyList',resp.data);
      if(type == 4) this.$set(areaList,'streetList',resp.data);
      // if(index == areaList.length - 1) {
        this.$set(this.form,'areaList',areaList);
        this.$forceUpdate()
      // }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加运营商";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id
      getOperator(id).then(response => {
        let data =  response.data || {};
        let areaList = data.areaList || []
        this.open = true;
        this.title = "修改运营商";
        areaList.forEach((item,index)=>{
          areaList[index].provinceCode = item.provinceCode ? Number(item.provinceCode) : '',
          areaList[index].cityCode = item.cityCode ? Number(item.cityCode) : '',
          areaList[index].countyCode = item.countyCode ? Number(item.countyCode) : '',
          areaList[index].townCode = item.townCode ? Number(item.townCode) : '',
          this.initLocationOptions1(item.provinceCode,2,index,areaList);
          this.initLocationOptions1(item.cityCode,3,index,areaList);
          this.initLocationOptions1(item.countyCode,4,index,areaList);
        })
        this.form = {
          ...data,areaList
        }
        // this.$set(this.form,'areaList',areaList);
        // this.$forceUpdate()
        
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          let areaList = [...form.areaList]
          let flag = ''
          areaList.map(item=>{
            if( this.$getNull(item.provinceCode) || this.$getNull(item.cityCode) || this.$getNull(item.countyCode) ) flag = '请填写完整负责区域数据'
          })
          if(flag) return  this.$modal.msgError(flag);
          this.popLodding = true
          if (this.form.id != undefined) {
            updateOperator(form).then(response => {
              this.popLodding = false
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error=>this.popLodding = false);
          } else {
            addOperator(form).then(response => {
              this.popLodding = false
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error=>this.popLodding = false);
          }
        }
      });
    },
  }
};
</script>